package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.NewsService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author kk
 */
@Slf4j
@Service
@Transactional
public class NewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements NewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 查询所有频道
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //设置分页参数
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //设置查询条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {//当前状态
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        if (dto.getChannelId() != null) {//图文频道id
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (StringUtils.isNotEmpty(dto.getKeyword())) {//关键字不为空
            queryWrapper.like(WmNews::getTitle, dto.getKeyword());//根据标题和关键字查
        }      //开始时间                    结束时间
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            queryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }                              //定时发布时间
        //查询数据
        page(page, queryWrapper);
        //封装返回结果
        PageResponseResult result = new PageResponseResult();
        result.setData(page.getRecords());
        result.setSize(dto.getSize());
        result.setCurrentPage(dto.getPage());
        result.setTotal((int) page.getTotal());
        return result;
    }

    /**
     * 发布文章或保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        //校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存或更新文章
        WmNews wmNews = saveOrUpdateNews(dto, user);
        //如果是保存草稿就返回成功
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //抽取文章内容中的图片地址
        List<String> urls = ectractUrlInfo(dto.getContent());
        //保存文章内容图片和素材之间的关系
        saveRelativeInfoForContent(urls, wmNews);
        //保存封面图片和素材之间的关系
        saveRelativeInfoForCover(urls, wmNews, dto);
        //完成文章的自动审核操作
        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //保存封面图片和素材之间的关系方法
    private void saveRelativeInfoForCover(List<String> urls, WmNews wmNews, WmNewsDto dto) {
        //获取封面图片
        List<String> images = dto.getImages();
        //处理封面为自动的情况
        if (dto.getType() == -1) {
            if (urls == null || urls.size() == 0) {
                wmNews.setType((short) 0);
            } else if (urls.size() < 3) {
                wmNews.setType((short) 1);
                images = urls.stream().limit(1).collect(Collectors.toList());
            } else {
                wmNews.setType((short) 3);
                images = urls.stream().limit(3).collect(Collectors.toList());
            }
            //更新文章封面类型
            updateById(wmNews);
        }
        //判断封面是否为无图
        if (images != null && images.size() > 0) {
            //保存关联关系
            saveRelativeInfo(images, wmNews, (byte) 1);
        }
    }

    //保存文章内容图片和素材之间的关系方法
    private void saveRelativeInfoForContent(List<String> urls, WmNews wmNews) {
        saveRelativeInfo(urls, wmNews, (byte) 0);
    }

    //抽取内容中所有的图片方法
    private List<String> ectractUrlInfo(String content) {
        List<String> urls = new ArrayList<>();
        List<Map> list = JSON.parseArray(content, Map.class);//json格式

        if (list != null && list.size() > 0) {//说明获取的有
            for (Map map : list) {
                if (map.get("type").equals("image")) {//判断获取的是图片
                    urls.add(map.get("value").toString());
                }
            }
        }
        return urls;
    }

    //保存或更新文章的数据方法
    private WmNews saveOrUpdateNews(WmNewsDto dto, WmUser user) {
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);//拷贝
        //处理图片
        String images = StringUtils.join(dto.getImages().toArray(), ",");
        wmNews.setImages(images);
        if (dto.getType() == -1) {
            wmNews.setType(null);
        }
        //新增文章
        if (dto.getId() == null) {//没有id表示没保存过这个文章就新增
            save(wmNews);
        } else {//有id执行文章的修改
            //删除文章和素材之间的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, dto.getId()));
            updateById(wmNews);
        }
        return wmNews;
    }

    //保存文章图片与素材的关系到数据库中方法
    private void saveRelativeInfo(List<String> urls, WmNews wmNews, byte type) {
        //用stream的distinct对urls去重
        urls = urls.stream().distinct().collect(Collectors.toList());
        //通过url地址查询素材素材的id
        if(urls.size() != 0){
            List<WmMaterial> wmMaterials = wmMaterialMapper
                    .selectList(
                            Wrappers
                                    .<WmMaterial>lambdaQuery()
                                    .in(WmMaterial::getUrl, urls));

            List<Integer> ids = wmMaterials.stream().map(item -> item.getId()).collect(Collectors.toList());
            //判断素材是否被删除过
            if (ids == null || ids.size() != urls.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);//抛出素材引用失效异常
            }
            //批量保存文章和素材之间的关系
            wmNewsMaterialMapper.batchInsert(wmNews.getId(), ids, type);
        }
    }
}



